# MadSnake - A snake game
# Copyright (C) 2020-2021  zhiqiang.bzq
#
# See LICENSE. And if you have interest in this project, join us.
#
# zhiqiang.bzq
# bzq23@foxmail.com

import time
import snake
import pygame
from color import Color
from common import *
import random
from pagectr import *
from pages.welcome_page import *
from pages.game_page import *
from pages.end_page import *

class Game(object):
  def __init__(self, name, automove_interval=1., good_interval=5.):
    self.name_ = name
    self.ground_size_ = Size(100, 100)
    self.ground_unit_size_ = Size(5, 5)
    self.scoreboardheight_ = 150
    
  def CovertEventToAction(self, pygame_event):
    # for 0 snake
    if pygame_event == pygame.K_w: return 0, Action.UP
    if pygame_event == pygame.K_s: return 0, Action.DOWN
    if pygame_event == pygame.K_a: return 0, Action.LEFT
    if pygame_event == pygame.K_d: return 0, Action.RIGHT
    if pygame_event == pygame.K_f: return 0, Action.SKILL
    # for 1 snake
    if pygame_event == pygame.K_UP: return 1, Action.UP
    if pygame_event == pygame.K_DOWN: return 1, Action.DOWN
    if pygame_event == pygame.K_LEFT: return 1, Action.LEFT
    if pygame_event == pygame.K_RIGHT: return 1, Action.RIGHT
    if pygame_event == pygame.K_SLASH: return 1, Action.SKILL
    return None, pygame_event

  def Run(self):
    pygame.init()
    screen = pygame.display.set_mode(
      (self.ground_unit_size_.width * self.ground_size_.width, \
       self.ground_unit_size_.height * self.ground_size_.height + self.scoreboardheight_)
    )
    pygame.display.set_caption(self.name_)
    clock = pygame.time.Clock()
    
    pc = PagesController()
    pc.AddPage(WelcomePage())
    pc.AddPage(GamePage(self.scoreboardheight_, self.ground_size_, self.ground_unit_size_))
    pc.AddPage(EndPage())

    while True:
      # accept events.
      for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
          snakeid, action = self.CovertEventToAction(event.key)
          pc.OnKeyboard(snakeid, action)
      screen.fill(Color.BLACK)
      pc.OnRender(screen)
      if pc.OnCheckOver():
        break
      # update & sleep.
      pygame.display.update()
      clock.tick(1000 / 60)

